package com.edu.atams.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.edu.atams.common.lang.Result;
import com.edu.atams.entity.Class;
import com.edu.atams.entity.Grade;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author czj666
 * @since 2021-10-09
 */
@RestController
@RequestMapping("/grade")
public class GradeController extends BaseController {

    @GetMapping("/list")
    public Result list(String year, String name){
        Page<Grade> page = gradeService.page(getPage(), new QueryWrapper<Grade>()
                .like(StrUtil.isNotBlank(year), "year", year)
                .like(StrUtil.isNotBlank(name), "name", name));
        return Result.succ(page);
    }

    @PostMapping("/save")
    @Transactional
    public Result save(@RequestBody Grade grade){
        List<Grade> list = gradeService.list(new QueryWrapper<Grade>().eq("name", grade.getName()).eq("year", grade.getYear()));
        System.out.println(list);
        if (list.size() > 0){
            return Result.fail("年级名称重复了");
        }else {
            gradeService.save(grade);
            return Result.succ("");
        }
    }

    @PostMapping("/remove")
    @Transactional
    public Result remove(@RequestBody Integer[] ids){
//        List<List<Class>> classList = new ArrayList<>();
        for (Integer id : ids) {

            List<Class> gradeId = classService.list(new QueryWrapper<Class>().eq("grade_id", id));
            if (gradeId.size() > 0){
                return Result.fail("请先删除年级里的班级");
            }
//            classList.add(gradeId);

        }
        gradeService.removeByIds(Arrays.asList(ids));
        return Result.succ("");


    }

    @PostMapping("/update")
    @Transactional
    public Result update(@RequestBody Grade grade){
        gradeService.updateById(grade);
        return Result.succ("");
    }

    //用于下拉框回显
    @GetMapping("/listAll")
    public Result listAll(){
        List<Grade> list = gradeService.list();
        List<Grade> grades = new ArrayList<>();
        for (Grade grade : list) {
            Grade grade1 = new Grade();
            grade1.setId(grade.getId());
            grade1.setYear(grade.getYear());
            grade1.setName(grade.getYear()+" "+grade.getName());
            grades.add(grade1);
        }
        return Result.succ(grades);
    }

}
